<template>
  <el-form :model="form" label-width="auto" style="max-width: 600px">
    <el-form-item label="推荐">
      <el-switch v-model="form.recommended" />
    </el-form-item>
    <el-form-item label="上架">
      <el-switch v-model="form.is_listed" />
    </el-form-item>
    <el-form-item>
      <el-button type="primary" @click.stop="onSubmit">确定</el-button>
      <el-button @click.stop="cancel">取消</el-button>
    </el-form-item>
  </el-form>
</template>

<script setup>
import { reactive, watchEffect } from 'vue';
import { ChangeProductStatus } from '../../api/product.js'
import showMessage from '../../untils/elMessage.js';

const emits = defineEmits(['confirmRS'])  //注册事件，声明事件
const form = reactive({
  is_listed:'',
  recommended:'',
  product_id: []
})

const props = defineProps({
  rs: Array
})
console.log(props.rs);

watchEffect(() => {
  // 过滤出要上架或则要推荐的商品
  form.product_id = props.rs.map((item) => item.product_id)

  // 如果是一件商品让其中传入的值自动变为自己的值，多件就变为false
  if (props.rs.length == 1) {
    console.log(props.rs.length);
    console.log(props.rs);
    form.is_listed = props.rs[0].is_listed ? true : false;
    form.recommended = props.rs[0].recommended ?true : false;
  }
  else {
    form.is_listed = false;
    form.recommended = false;
  }
})

// 点击确认
const onSubmit = () => {
  if (!!props.rs) {
    form.is_listed = form.is_listed ? 1 : 0;
    form.recommended = form.recommended ? 1 : 0;
    console.log('Submitted form data:', form);
    ChangeProductStatus({
      product_id: form.product_id,
      is_listed: form.is_listed,
      recommended: form.recommended,
    }).then(res => {
      if (res.msgType == 8000) {
        emits('confirmRS', form)
      }
      showMessage(res)
    })
  }
  else {
    // AddProduct({
    //   product_name: form.name,
    //   image_url: form.imageUrl,
    //   description: form.description,
    //   price: form.price,
    //   weight: form.weight,
    //   category_id: form.categories,
    //   inventory: form.inventory,
    //   created_at: form.created
    // }).then(res => {
    //   if (res.msgType == 8000) {
    //     emits('confirm')
    //   }
    //   showMessage(res)

    // })
  }
};

// 点击取消，重置输入框
const cancel = () => {
  form.is_listed = false;
  form.recommended = false;
  console.log(form);
}


</script>

<style lang="less" scoped></style>